package de.hs.rm;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import javax.management.InstanceAlreadyExistsException;
import javax.management.InstanceNotFoundException;
import javax.management.IntrospectionException;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServerConnection;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.ReflectionException;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;

public class Tester {

	private TesterGUI gui = null;
	
	private JMXConnector jmxConnector = null;
	private JMXServiceURL serviceUrl = null;
	private MBeanServerConnection mBeanServerConnection = null;	
	
	public Tester()
	{	   
	    gui = new TesterGUI();
	    String host = "localhost";
        int port = 9999;
        String url = "service:jmx:rmi:///jndi/rmi://" + host + ":" + port + "/jmxrmi";
        try {
			serviceUrl = new JMXServiceURL(url);
			jmxConnector = JMXConnectorFactory.connect(serviceUrl, null);
		    mBeanServerConnection = jmxConnector.getMBeanServerConnection();
		    populateLists();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        gui.btRegister.addActionListener(new RegisterListener());
        gui.btUnregister.addActionListener(new UnregisterListener());
		
	}
	
	private void populateLists() {
		try {
			String[] domains = mBeanServerConnection.getDomains();
			for (int i = 0; i < domains.length; i++)
	        {
				ObjectName searchObjName = new ObjectName(domains[i] + ":*");
	        	Set<ObjectName> set = mBeanServerConnection.queryNames(searchObjName, null);
	        	Iterator<ObjectName>  it = set.iterator();
	        	while (it.hasNext())
	        	{
	        		ObjectName objName = it.next();
	        		gui.lRegListModel.addElement(objName.toString());
	        		//MBeanInfo mBeanInfo = mBeanServerConnection.getMBeanInfo(objName);
	        	}
	        }
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedObjectNameException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

	private class RegisterListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
        	try {
        		if(!gui.lRegister.isSelectionEmpty())
        		{
		        	String sOldObjName = gui.lRegister.getSelectedValue().toString();//"de.hs.rm.jmx:type=HelloWorldTestCase"
		        	String sClassName = "";//gui.tfRegisterClassName.getText();//"de.hs.rm.jmx.HelloWorld"
	
	        		ObjectName oldObjName = new ObjectName(sOldObjName);
	        		MBeanInfo mBeanInfo = mBeanServerConnection.getMBeanInfo(oldObjName);
	        		sClassName = mBeanInfo.getClassName();
		        	
		        	
		        	String sNewObjName = sOldObjName + "Test";//"de.hs.rm.jmx:type=HelloWorldTestCase"
		    		ObjectName newObjName = new ObjectName(sNewObjName);
					if(!mBeanServerConnection.isRegistered(newObjName))
					{
						gui.updateTaLog("Registering MBean: " + sClassName);
						mBeanServerConnection.createMBean(sClassName, newObjName);
						gui.lUnregListModel.addElement(sNewObjName);
					}
					else
					{
						gui.updateTaLog("Mbean: " + sClassName + "does not exist!");
					}
        		}
      		} catch (InstanceAlreadyExistsException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (MBeanRegistrationException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (NotCompliantMBeanException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (ReflectionException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (MBeanException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (IOException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (MalformedObjectNameException e) {
      			// TODO Auto-generated catch block
      			e.printStackTrace();
      		} catch (InstanceNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IntrospectionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
        }       
    }
	
	private class UnregisterListener implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent arg0)
        {
        	if(!gui.lUnregister.isSelectionEmpty())
    		{
              
	        	String mBeanName = gui.lUnregister.getSelectedValue().toString();
	        	int selectedIndex = gui.lUnregister.getSelectedIndex();
	    		ObjectName objName;
	    		try {
					objName = new ObjectName(mBeanName);//"de.hs.rm.jmx:type=HelloWorldTestCase");
					if(mBeanServerConnection.isRegistered(objName))
					{
						gui.updateTaLog("Unregistering MBean: " + mBeanName);
						mBeanServerConnection.unregisterMBean(objName);
						gui.lUnregListModel.remove(selectedIndex);
					}
					else
					{
						gui.updateTaLog("Mbean: " + mBeanName + "is not registered on the server!");
					}
	    	
	      		} catch (MBeanRegistrationException e) {
	      			// TODO Auto-generated catch block
	      			e.printStackTrace();
	      		} catch (IOException e) {
	      			// TODO Auto-generated catch block
	      			e.printStackTrace();
	      		} catch (MalformedObjectNameException e) {
	      			// TODO Auto-generated catch block
	      			e.printStackTrace();
	      		} catch (InstanceNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
    		}
        }       
    }
	
	
	public static void main(String[] args) throws IOException, InterruptedException
	{
	    new Tester();	    
	}

}
